package mxmf.spi;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.event.service.spi.EventListenerRegistry;
import org.hibernate.event.spi.EventType;
import org.hibernate.event.spi.PostDeleteEventListener;
import org.hibernate.event.spi.PostInsertEventListener;
import org.hibernate.event.spi.PostUpdateEventListener;
import org.hibernate.internal.SessionFactoryImpl;
import org.hibernate.persister.entity.EntityPersister;
import org.springframework.beans.factory.annotation.Autowired;

@SuppressWarnings("serial")
public abstract class AbstractPostListener implements PostUpdateEventListener, PostInsertEventListener, PostDeleteEventListener{
		@Autowired 
	    protected EntityManager entityManager;  

		@PostConstruct
		public void init() {
			Session session = (Session) entityManager.getDelegate();
			SessionFactory sessionFactory = session.getSessionFactory();
			EventListenerRegistry registry = ((SessionFactoryImpl) sessionFactory).getServiceRegistry().getService(  
	                EventListenerRegistry.class);  
	        registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(this);  
	        registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(this);  
	        registry.getEventListenerGroup(EventType.POST_DELETE).appendListener(this);  
	    }

		@Override
		public boolean requiresPostCommitHanding(EntityPersister persister) {
			return false;
		}

}
